package com.zhiwei.service;

import com.zhiwei.configuration.SysConf;
import com.zhiwei.tool.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;

/**
 * @author bao
 * @description 将服务器文件展示至前端页面展示
 * @date 2021/9/29
 */
@Slf4j
@Service
public class WebService {

    public static final String REG_IMG = ".+(.jpeg|.jpg|.gif|.bmp|.png|.imge)$";
    public static final String INDEX = "index.html";

    @Autowired
    SysConf sysConf;

    /**
     * @param request  文件的相对位置和具体文件名 doc/2019/09/example.xml
     * @param response HttpServletResponse 用于返回文件传输
     * @throws IOException
     */
    public void webFile(HttpServletRequest request, HttpServletResponse response) {
        String url = request.getRequestURI().substring(1);
        if (Utils.isNull(url)){
            url = INDEX;
        }
        String fileName = Utils.fileName(url);
        String filePath = Utils.filePathJoin(sysConf.getWebPath(), url);
        try {
            response.reset();
            boolean isIndex = fileName.endsWith(".html");
            if (isIndex) {
                response.setContentType("text/html;charset=UTF-8");
            }
            if (Pattern.compile(REG_IMG).matcher(fileName).find()) {
                BufferedImage image = ImageIO.read(new File(filePath));
                ImageIO.write(image, Utils.suffix(fileName), response.getOutputStream());
                return;
            }
            if (fileName.endsWith(".js")) {
                response.addHeader("Content-Type", "application/javascript");
            }
            if (fileName.endsWith(".css")) {
                response.addHeader("Content-Type", "text/css");
            }
            if (!isIndex) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
            //对输出流进行压缩
            writeGzipResponse(filePath, response);
        } catch (Exception e) {
            log.error("获取网页文件异常", e);
        }
    }

    /**
     * 响应gzip压缩流
     */
    private void writeGzipResponse(String filePath, HttpServletResponse response) {
        File file = new File(filePath);
        if (!file.exists()) {
            log.debug("找不到指定文件：" + file.getAbsolutePath());
        }
        FileInputStream inputStream = null;
        GZIPOutputStream gzip = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            File gzipFile = new File(filePath + ".gz");
            if (!gzipFile.exists()) {
                gzipFile.createNewFile();
                inputStream = new FileInputStream(file);
                gzip = new GZIPOutputStream(new FileOutputStream(gzipFile));
                Utils.transStream(inputStream, gzip);
            }
            //设置压缩格式
            response.addHeader("Content-Encoding", "gzip");
            //设置新文件大小
            response.addHeader("Content-Length", String.valueOf(gzipFile.length()));
            Utils.transStream(new FileInputStream(gzipFile), outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            Utils.safeClose(gzip);
            Utils.safeClose(inputStream);
            Utils.safeClose(outputStream);
        }
    }

}
